/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jfonia.model.relations;

import org.jfonia.connect5.basics.ValueNode;
import org.jfonia.connect5.basics.Node;
import org.jfonia.connect5.intervals.Interval;
import org.jfonia.connect5.intervals.ListObserver;
import org.jfonia.connect5.relations.Relation;
import org.jfonia.model.PerformanceSequence;
import org.jfonia.model.QuantizerNode;
import org.jfonia.model.Staff;

/**
 *s
 * @author jannes
 */
public class TimeToTicksRelation implements Relation,ListObserver{
    private ValueNode<Boolean> notationLockNode;
    private PerformanceSequence sequence;
    private QuantizerNode quantizerNode;
    private Staff staff;    

    public TimeToTicksRelation(PerformanceSequence sequence, QuantizerNode quantizerNode,Staff staff,ValueNode<Boolean> notationLockNode){
        this.sequence = sequence;
        this.quantizerNode =  quantizerNode;
        this.staff = staff;
        this.notationLockNode = notationLockNode;
        switchOn();
    }

    private void updateOffset(){
        if(!notationLockNode.getValue()){
            try{                
                quantizerNode.getQuantizer().updateOffsets(sequence,staff);                
            }catch(Exception exc){}
        }
    }

    public void switchOn(){
        sequence.addObserver(this);
        quantizerNode.addObserver(this);
        notationLockNode.addObserver(this);
        updateOffset();
    }

    public void switchOff(){
        sequence.removeObserver(this);
        quantizerNode.removeObserver(this);
        notationLockNode.removeObserver(this);
    }

    public void onNotify(Object source) {
        if(source == quantizerNode || source == notationLockNode){            
            updateOffset();
        }
    }

    public void intervalAdded(Interval interval) {
        updateOffset();        
    }

    public void intervalRemoved(Interval interval, int i) {
        updateOffset();        
    }

    public void intervalEndChanged(Interval interval) {
        updateOffset();        
    }
}
